package com.shawbs.vueblog.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.shawbs.vueblog.comom.ErrorCode;
import com.shawbs.vueblog.comom.Result;
import com.shawbs.vueblog.comom.param.LoginParam;
import com.shawbs.vueblog.entity.User;
import com.shawbs.vueblog.service.UserService;
import com.shawbs.vueblog.util.Common;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.hutool.crypto.SecureUtil;
import com.shawbs.vueblog.util.JwtUtils;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.shiro.SecurityUtils;

@Api(tags = "用户操作")
@RestController
@RequestMapping("/account")
public class AccountController {

    @Autowired
    UserService userService;

    @Autowired
    JwtUtils jwtUtils;

//    @Resource
//    RedisUtil redisUtil;

    @ApiOperation(value = "用户登录",notes ="json串参数：username:用户名，password:用户密码")
    @PostMapping("/login")
    public Result login(@RequestBody LoginParam loginParam, HttpServletResponse response) throws IllegalAccessException {
        String username = loginParam.getUsername();
        String password = loginParam.getPassword();

        User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
        Assert.notNull(ErrorCode.USER_NONE_ERROR.getCode(), ErrorCode.USER_NONE_ERROR.getMsg());

        if(!user.getPassword().equals(SecureUtil.sha256(password))) {
            return Result.fail(ErrorCode.PASSWORD_ERROR.getCode(),ErrorCode.PARAM_ERROR.getMsg());
        }

        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);
        response.setHeader("Access-control-Expose-Headers", "Authorization");

        ArrayList arrayList = new ArrayList<>();
        arrayList.add("password");

        HashMap<String,Object> hashMap = Common.filterObjectKey(user,arrayList);

        hashMap.put("token",jwt);

//        redisUtil.set("'token_'" + jwt, JSON.toJSONString(user));

        return Result.success(hashMap);

    }

    @ApiOperation(value = "退出登录")
    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }
}
